package org.myorg.v3;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;

public class S3 extends Para3 {
	static int best_p;
	static double best_v;
	static FPeople3 best_people;


	public static String ga(int geneLength,
			int peopleNum, double p_cross,
			double p_mut, long i_num,Fc3 fc,
			double[] data) {

		String res = "";

		long start_time = System.currentTimeMillis();
		FPeople3 my_p = new FPeople3(peopleNum,geneLength);
		FEvolution3 my_e = new FEvolution3(0.1, p_cross, p_mut);
		fc.caculate(my_p.persons);
		
		best_people = new FPeople3(my_p);

		double best = 0;
		boolean[] mark = new boolean[data.length];
		for (boolean bm : mark) {
			bm = false;
		}

		int count = 0;

		for (int i=0; i < i_num; i++) {

			/*if current best value are letter than global best value,
			 * replace global best value with current value
			 */
			double best_fitness = my_p.getBest().fitness;
			if( best_fitness > best) {

				//best_people=new FPeople3(my_p);							
				//best = best_people.getPersons()[best_people.getBest(sfc)].fitness;
				best = best_fitness;
				
				double b_v = fc.org_value(my_p.getBest());
				if (count < data.length && !mark[count] && b_v < data[count] ) {
					res = res + "\t" + (System.currentTimeMillis() - start_time) +
					"\t" + i + "\t" + b_v;
					mark[count] = true;
					count++;
					if (count == data.length) {
						return res;
					}
				}
			}

			//my_e.select();
			my_e.select(my_p);
			my_e.crossOver(my_p);
			my_e.mutation(my_p);
			fc.caculate(my_p.persons);
		}

		return res;
	}
	
	public static void main(String[] arg) {
		System.out.println("enter main");

		//reserve results
		String cmd = "mkdir -p ./res";
		RWF3.execmd(cmd);
		
		//for running much programmers
		String mark = RWF3.mkMark("./res/smark", sfc);

		//put different results of different program to different directory 
		cmd = "mkdir -p " + spath;
		RWF3.execmd(cmd);


		for (int i = 0; i < ln; i++) {

			long st = System.currentTimeMillis();
			String r = ga(geneLength, spn, p_cross, p_mut, i_num, sfc, smag);
			long rt = System.currentTimeMillis() - st;
			System.out.println(i + "run time is " + rt);
			
			r = r + "\n";
			RWF3.wlf(r.getBytes(),spath + "/s_r" + mark);
			
		}
		
		System.out.println("Game over");
	}

}
